package com.anivia.common.core.model.vo;


import com.anivia.common.core.constant.CommonStant;
import com.anivia.common.core.enums.BaseEnum;
import com.anivia.common.core.enums.CommonResponseEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * 公共的返回值对象
 *
 * @author wangj
 */
@Schema
@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = CommonResponseEnum.SUCCESS.getCode();
    public static final String SUCCESS_MSG = CommonResponseEnum.SUCCESS.getDesc();

    /**
     * 失败
     */
    public static final int FAIL = CommonResponseEnum.FAILED.getCode();
    public static final String FAIL_MSG = CommonResponseEnum.FAILED.getDesc();

    @Schema(description = "响应码")
    private Integer code;

    @Schema(description = "响应消息")
    private String msg;

    @Schema(description = "响应数据")
    private T data;

    private String requestId = MDC.get(CommonStant.TRACE_ID);

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data, String message) {
        return restResult(data, SUCCESS, message);
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    public static <T> R<T> fail(BaseEnum baseEnum) {
        return restResult(null, baseEnum.getCode(), baseEnum.getDesc());
    }

    public static <T> R<T> fail(int code, String msg, T data) {
        return restResult(data, code, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}